package demo;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.Statement;

/*
 *  JDBC API 详解 Connection
 * */
public class JDBCDemo3_Connection {
    public static void main(String[] args) throws Exception {
        // 1.注册驱动  (jdk5后此步骤可省略不写)
        // Class.forName("com.mysql.jdbc.Driver");

        // 2.获取连接
        String url = "jdbc:mysql://127.0.0.1:3308/my_java?useSSL=false";
        String username = "root";
        String password = "123456";
        Connection conn = DriverManager.getConnection(url, username, password);

        // 3.定义sql
        String sql1 = "UPDATE account SET money =3000 WHERE id =1";
        String sql2 = "UPDATE account SET money =3000 WHERE id =2";

        // 4.获取执行sql的对象Statement
        Statement stmt = conn.createStatement();

        // 5.执行sql（可能会报错）
        try {
            // 开启事务
            conn.setAutoCommit(false);
            // 5.执行sql
            int count1 = stmt.executeUpdate(sql1); // 受影响的行数
            System.out.println(count1); // 打印
            int i = 3 / 0;
            // 5.执行sql
            System.out.println(stmt.executeUpdate(sql2)); // 打印
            // 提交事务
            conn.commit();
        } catch (Exception throwables) {
            // 回滚事务
            conn.rollback();
            throw new RuntimeException();
        }


        // 释放资源
        stmt.close();
        conn.close();
    }
}
